using System;
using System.ComponentModel;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.Runtime;
using Microsoft.SharePoint.WorkflowActions;

namespace DP.Sharepoint.Workflow
{
    public partial class AddListItemPermissionAssigment : Activity
    {
        public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context",
                                                                                         typeof (WorkflowContext),
                                                                                         typeof (
                                                                                             AddListItemPermissionAssigment
                                                                                             ));


        public static DependencyProperty ListIdProperty = DependencyProperty.Register("ListId", typeof (string),
                                                                                      typeof (
                                                                                          AddListItemPermissionAssigment
                                                                                          ));


        public static DependencyProperty ListItemProperty = DependencyProperty.Register("ListItem", typeof (int),
                                                                                        typeof (
                                                                                            AddListItemPermissionAssigment
                                                                                            ));

        public static DependencyProperty PermissionLevelProperty = DependencyProperty.Register("PermissionLevel",
                                                                                               typeof (string),
                                                                                               typeof (
                                                                                                   AddListItemPermissionAssigment
                                                                                                   ));


        public static DependencyProperty UserNameProperty = DependencyProperty.Register("UserName", typeof (string),
                                                                                        typeof (
                                                                                            AddListItemPermissionAssigment
                                                                                            ));

        public AddListItemPermissionAssigment()
        {
            InitializeComponent();
        }

        [Description("Context")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public WorkflowContext __Context
        {
            get { return ((WorkflowContext) (base.GetValue(__ContextProperty))); }
            set { base.SetValue(__ContextProperty, value); }
        }

        [Description("ListId")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string ListId
        {
            get { return ((string) (base.GetValue(ListIdProperty))); }
            set { base.SetValue(ListIdProperty, value); }
        }

        [Description("ListItem")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public int ListItem
        {
            get { return ((int) (base.GetValue(ListItemProperty))); }
            set { base.SetValue(ListItemProperty, value); }
        }

        [Description("UserName")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string UserName
        {
            get { return ((string) (base.GetValue(UserNameProperty))); }
            set { base.SetValue(UserNameProperty, value); }
        }


        [Description("PermissionLevel")]
        [ValidationOption(ValidationOption.Required)]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string PermissionLevel
        {
            get { return ((string) (base.GetValue(PermissionLevelProperty))); }
            set { base.SetValue(PermissionLevelProperty, value); }
        }


        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                PermissionRequest myGrantRequest = new PermissionRequest();

                myGrantRequest.RequestType = PermissionActionType.Grant;
                myGrantRequest.ItemId = ListItem;
                myGrantRequest.ListID = new Guid(ListId);
                myGrantRequest.SiteID = __Context.Site.ID;
                myGrantRequest.WebID = __Context.Web.ID;
                myGrantRequest.User = UserName;
                myGrantRequest.PermissionLevel = Common.ProcessStringField(executionContext, PermissionLevel);


                WorkflowEnvironment.WorkBatch.Add(PermissionsService.Instance, myGrantRequest);


                //run in context of sharpoints system account because user might not have permissions to grant permisions (Beware of the security risk here)


                //SPSecurity.RunWithElevatedPrivileges(delegate()
                // {
                //     using (SPSite site = new SPSite(__Context.Site.ID))
                //     {
                //         using (SPWeb web = site.AllWebs[__Context.Web.ID])
                //         {

                //             SPList List = web.Lists[new Guid(this.ListId)];

                //             SPListItem listItem = List.GetItemById(this.ListItem);

                //             string permission = Common.ProcessStringField(executionContext, this.PermissionLevel);

                //             if (!Common.IsUserRoleAssigned(__Context, this.ListId, this.ListItem, permission, this.UserName))
                //             {
                //                 if (!listItem.HasUniqueRoleAssignments)
                //                 {
                //                     listItem.BreakRoleInheritance(true);
                //                 }

                //                 Common.RemoveListItemLimitedPermissions(listItem);

                //                 Common.RemoveListItemPermissionEntry(listItem, this.UserName, false);

                //                 listItem = Common.SetItemPermissions(web, listItem, permission, this.UserName);

                //                 listItem.Update();

                //             }

                //         }
                //     }

                // });
            }
            catch (Exception e)
            {
                Common.LogExceptionToWorkflowHistory(e, executionContext, WorkflowInstanceId);

                throw;
            }
            return ActivityExecutionStatus.Closed;
        }
    }
}